package com.trt.files.controller;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.model.Filters;
import com.trt.api.controller.files.FileUploaderControllerApi;
import com.trt.enums.ResponseStatusEnum;
import com.trt.exception.ApiException;
import com.trt.files.config.MinIOConfig;
import com.trt.files.resource.FileResource;
import com.trt.files.service.UploaderService;
import com.trt.pojo.dto.AdminUserBO;
import com.trt.utils.AliImageReviewUtils;
import com.trt.utils.ApiResult;
import com.trt.utils.FileUtils;
import com.trt.utils.MinIOUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author tanrentao
 * @date 2021-12-03
 * @desc
 */
@RestController
public class FileUploaderController implements FileUploaderControllerApi {

    final static Logger logger = LoggerFactory.getLogger(FileUploaderController.class);

    @Autowired
    private UploaderService uploaderService;

    @Autowired
    private FileResource fileResource;

    @Autowired
    private AliImageReviewUtils aliImageReviewUtils;

    @Autowired
    private MinIOConfig minIOConfig;

    @Autowired
    private GridFSBucket gridFSBucket;

    public static final String FAILED_IMAGE_URL = "https://imooc-news.oss-cn-shanghai.aliyuncs.com/image/faild.jpeg"; // 审核失败后错误图片

    @Override
    public ApiResult uploadToFdfsFace(String userId, MultipartFile file) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return ApiResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }

        String path = "";
        if (file != null) {
            // 获得文件上传的名称
            String fileName = file.getOriginalFilename();
            // 判断文件名不能为空
            if (StringUtils.isNotBlank(fileName)) {
                String fileNameArr[] = fileName.split("\\.");
                // 获得后缀
                String suffix = fileNameArr[fileNameArr.length - 1];
                // 判断后缀符合我们的预定义规范
                if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg")) {
                    return ApiResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
                }
                // 上传
                path = uploaderService.uploadFdfs(file, suffix);
            } else {
                return ApiResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
            }
        } else {
            return ApiResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        logger.info("path = " + path);

        String finalPath = "";
        if (StringUtils.isNotBlank(path)) {
            finalPath = fileResource.getHost() + path;
        } else {
            return ApiResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }

        // return ApiResult.success(doAliImageReview(finalPath));
        return ApiResult.success(finalPath);
    }

    @Override
    public ApiResult uploadToOSSFace(String userId, MultipartFile file) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return ApiResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }

        String path = "";
        if (file != null) {
            // 获得文件上传的名称
            String fileName = file.getOriginalFilename();
            // 判断文件名不能为空
            if (StringUtils.isNotBlank(fileName)) {
                String fileNameArr[] = fileName.split("\\.");
                // 获得后缀
                String suffix = fileNameArr[fileNameArr.length - 1];
                // 判断后缀符合我们的预定义规范
                if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg")) {
                    return ApiResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
                }
                // 上传
                path = uploaderService.uploadOSS(userId, file, suffix);
            } else {
                return ApiResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
            }
        } else {
            return ApiResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        logger.info("path = " + path);

        String finalPath = "";
        if (StringUtils.isNotBlank(path)) {
            finalPath = fileResource.getOssHost() + path;
        } else {
            return ApiResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }

        //return ApiResult.success(doAliImageReview(finalPath));
        return ApiResult.success(finalPath);
    }

    @Override
    public ApiResult uploadToMinIOFace(String userId, MultipartFile file) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return ApiResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }

        String path = "";
        if (file != null) {
            // 获得文件上传的名称
            String fileName = file.getOriginalFilename();
            // 判断文件名不能为空
            if (StringUtils.isNotBlank(fileName)) {
                String fileNameArr[] = fileName.split("\\.");
                // 获得后缀
                String suffix = fileNameArr[fileNameArr.length - 1];
                // 判断后缀符合我们的预定义规范
                if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg")) {
                    return ApiResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
                }
                // 上传
                MinIOUtils.uploadFile(minIOConfig.getBucketName(), fileName, file.getInputStream());
                path = minIOConfig.getFileHost() + "/" +minIOConfig.getBucketName() + "/" + fileName;
            } else {
                return ApiResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
            }
        } else {
            return ApiResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        logger.info("path = " + path);

        //return ApiResult.success(doAliImageReview(path));
        return ApiResult.success(path);
    }

    /**
     *
     * 图片自动审核功能
     *
     * 内容安全
     * 内容安全基于深度学习技术，提供图片、视频、语音、文字、网页等多媒体的内容风险智能识别和审核服务，
     * 帮助用户发现色情、暴恐、政治敏感等风险内容，大幅度降低人工审核成本。
     *
     * 创建阿里云子账号
     * RAM访问控制台
     * https://ram.console.aliyun.com/users/new
     * 在AliTextReviewUtils文件中使用
     * 需要授权 AliyunYundunGreenWebFullAccess
     *
     *
     * @param imageUrl
     * @return
     */
    private String doAliImageReview(String imageUrl) {
        /**
         * fastdfs 默认存在于内网，无法被阿里云内容管理服务检查到
         * 需要配置到公网才行：
         * 1. 内网穿透，natppp/花生壳/ngrok/闪库内网穿透
         * 2. 路由配置端口映射
         * 3. fdfs 发布到云服务器
         */
        boolean result = false;
        try {
            result = aliImageReviewUtils.reviewImage(imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!result) {
            return FAILED_IMAGE_URL;
        }

        return imageUrl;
    }

    @Override
    public ApiResult uploadToGridFS(AdminUserBO adminUserBO) throws Exception {
        // 1.获得图片的base64字符串
        String img64 = adminUserBO.getImg64();

        // 2.将base64字符串转换为byte数组
        byte[] bytes = new BASE64Decoder().decodeBuffer(img64);

        // 3.转换为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

        // 4.上传到gridfs中
        ObjectId objectId = gridFSBucket.uploadFromStream(adminUserBO.getUsername() + ".png", inputStream);

        // 5.获得文件在gridfs中的主键id
        String fileId = objectId.toString();

        return ApiResult.success(fileId);
    }

    @Override
    public void readInGridFS(String faceId, HttpServletResponse response) throws Exception {
        if (StringUtils.isBlank(faceId) || faceId.equalsIgnoreCase("null")) {
            ApiException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }

        // 1. 从gridfs中读取
        File adminFace = readGridFSByFaceId(faceId);

        // 2. 把人脸图片输出到浏览器
        FileUtils.downloadFileByStream(response, adminFace);
    }

    private File readGridFSByFaceId(String faceId) throws Exception {
        GridFSFindIterable gridFSFiles = gridFSBucket.find(Filters.eq("_id", new ObjectId(faceId)));
        GridFSFile gridFSFile = gridFSFiles.first();
        if (gridFSFile == null) {
            ApiException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }
        String fileName = gridFSFile.getFilename();
        System.out.println(fileName);

        // 获取文件流，保存文件到本地或者服务器的临时目录
        File fileTemp = new File("/workspace/temp_face");
        if (!fileTemp.exists()) {
            fileTemp.mkdirs();
        }

        File myFile = new File("/workspace/temp_face/" + fileName);

        // 创建文件输出流
        OutputStream os = new FileOutputStream(myFile);

        // 下载到服务器或者本地
        gridFSBucket.downloadToStream(new ObjectId(faceId), os);

        return myFile;
    }

}
